package com.hujia.service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.hujia.entity.Area;
import com.hujia.rs.redis.RedisProvider;

import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;

public class AreaService {

	/**
	 * 加载区域数据
	 * @return
	 */
	public Future<Void> loadAreaData() {
		Future<Void> future = Future.future();
		InputStream is = null;
		try {
			is = Area.class.getClassLoader().getResourceAsStream("areas.json");
			String cityData = IOUtils.toString(is, StandardCharsets.UTF_8);
			JsonArray citys = new JsonArray(cityData);
			if (citys == null || citys.isEmpty()) {
				future.fail("区域数据读取失败");
			}

			// 存一个region的key
			// 存一个城市的有序集合, key="city-"+城市的code
			JsonObject regions = new JsonObject();
			Map<String, List<String>> areaMap = new HashMap<String, List<String>>();

			for (int i = 0; i < citys.size(); i++) {
				JsonObject jsonObject = citys.getJsonObject(i);
				String code = jsonObject.getString("code");
				regions.put(String.format("region-%s", code), jsonObject.toString());

				String cityKey = String.format("city-%s", jsonObject.getString("cityCode"));

				List<String> areaList = areaMap.get(cityKey);
				if (areaList == null) {
					areaList = new ArrayList<String>();
					areaMap.put(cityKey, areaList);
				}
				areaList.add(code);
			}

			RedisClient redisClient = RedisProvider.getRedisClient();
			redisClient.mset(regions, msetRes -> {
				if (msetRes.succeeded()) {
					Iterator<String> keys = areaMap.keySet().iterator();
					while (keys.hasNext()) {
						String key = keys.next();
						List<String> value = areaMap.get(key);
						redisClient.del(key, rss -> {
							if (rss.succeeded()) {
								redisClient.saddMany(key, value, rs -> {
									if (rs.failed()) {
										future.fail(rs.cause().getMessage());
									}

								});
							}
						});

					}
					System.out.println("加载区域数据完成.");
					future.complete();
				}
			});
		} catch (Exception ex) {
			future.fail(ex.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return future;
	}
}
